﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using DynamicProxyCore;

namespace WpfApplication1
{
	/// <summary>
	/// Interaction logic for MainWindow.xaml
	/// </summary>
	public partial class MainWindow : INotifyPropertyChanged
	{
		static Random _random = new Random();
		const int _maxDeep = 5;
		static int _deep = 0;
		private IEnumerable<dynamic> _items;
		public IEnumerable<dynamic> Items
		{
			get { return _items; }
			set { _items = value; OnPropertyChanged("Items"); }
		}

		private IEnumerable<dynamic> _selectedItems;
		public IEnumerable<dynamic> SelectedItems
		{
			get { return _selectedItems; }
			set { _selectedItems = value; OnPropertyChanged("SelectedItems"); }
		}

		public MainWindow()
		{
			InitializeComponent();
			DataContext = this;
			Items = new[] { DynamicProxy.Create(CreateRegions().First()).AddProperty<bool>("IsSelected") };
		}


		private static IEnumerable<Region> CreateRegions()
		{
			if(_deep == _maxDeep)
			{
				return Enumerable.Empty<Region>();
			}
			_deep++;
			return Enumerable.Range(1, _random.Next(1, 5)).Select(i => new Region{ Index = _random.Next(), Name=string.Format("Region{0}{1}", _random.Next(), i),SubRegions = CreateRegions()}).ToList();
		}

		IEnumerable<Region> GetSelectedItems(IEnumerable<dynamic> items)
		{
			return items.Where(x => x.IsSelected).Concat(items.SelectMany(x => GetSelectedItems((IEnumerable<dynamic>)x.SubRegions))).Select(x=>(Region)x);
		}

		private void ButtonClick(object sender, RoutedEventArgs e)
		{
			var res = GetSelectedItems(Items).Take(10).ToList();
			SelectedItems = res;
		}

		public event PropertyChangedEventHandler PropertyChanged;

		public void OnPropertyChanged(string propertName)
		{
			if (PropertyChanged != null)
			{
				PropertyChanged(this, new PropertyChangedEventArgs(propertName));
			}
		}
	}
}

